{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'http://www.baidu.com' page is 364909 bytes\n",
      "'http://www.baidu.com' page is 364915 bytes\n",
      "'http://www.baidu.com' page is 364903 bytes\n",
      "'http://www.baidu.com' page is 364914 bytes\n",
      "'http://www.baidu.com' page is 364909 bytes\n",
      "'http://www.baidu.com' page is 364902 bytes\n"
     ]
    }
   ],
   "source": [
    "# 并发编程\n",
    "# ThreadPoolExecutor  线程池\n",
    "# ProcessPoolExecutor 并行计算\n",
    "from concurrent.futures import  ThreadPoolExecutor\n",
    "\n",
    "import concurrent.futures\n",
    "import urllib.request\n",
    "\n",
    "URLS = ['http://www.baidu.com',\n",
    "        'http://www.baidu.com',\n",
    "        'http://www.baidu.com',\n",
    "        'http://www.baidu.com',\n",
    "        'http://www.baidu.com',\n",
    "        'http://www.baidu.com'\n",
    "]\n",
    "\n",
    "def load_url(url, timeout):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "# 线程池，最大允许并发数：2\n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:\n",
    "    # 提交任务到线程池中执行\n",
    "    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n",
    "    # 使用as_completed()函数迭代Future对象的集合\n",
    "    for future in concurrent.futures.as_completed(future_to_url):\n",
    "        url = future_to_url[future]\n",
    "        try:\n",
    "            # 获取任务的结果\n",
    "            data = future.result()\n",
    "        except Exception as exc:\n",
    "            print('%r generated an exception: %s' % (url, exc))\n",
    "        else:\n",
    "            print('%r page is %d bytes' % (url, len(data)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.11.0 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
